//
//  StatusPictureView.swift
//  Practice
//
//  Created by miaozhihui on 2017/3/1.
//  Copyright © 2017年 DeKuTree. All rights reserved.
//

import UIKit

class StatusPictureView: UIView {
    
    var viewModel: StatusViewModel? {
        didSet{
            calcViewSize()
            urls = viewModel?.picURLs
        }
    }
    
    /// 根据视图模型的配图视图大小，调整显示内容
    private func calcViewSize() {
        // 单图
        if viewModel?.picURLs?.count == 1 {
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: StatusPictureViewOutterMargin, width: viewModel?.pictureViewSize.width ?? 0, height: (viewModel?.pictureViewSize.height ?? 0) - 12)
        } else { // 多图
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: StatusPictureViewOutterMargin, width: StatusPictureItemWidth, height: StatusPictureItemWidth)
        }
        // 配图视图的高度
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    @IBOutlet weak var heightCons: NSLayoutConstraint!
    
    /// 缩略图数组
    private var urls: [StatusPicture]? {
        didSet{
            // 隐藏所有子视图
            for v in subviews {
                v.isHidden = true
            }
            var index = 0
            for url in urls ?? [] {
                let iv = subviews[index] as! UIImageView
                // 4张图像处理
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                iv.zh_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                iv.isHidden = false
                index += 1
            }
        }
    }
    
    
    override func awakeFromNib() {
        setupUI()
    }
    
}

// MARK: - 设置界面
extension StatusPictureView {
    
    fileprivate func setupUI() {
        
        // 设置背景颜色
        backgroundColor = superview?.backgroundColor
        // 超出边界的内容不显示
        clipsToBounds = true
        let rect = CGRect(x: 0, y: StatusPictureViewOutterMargin, width: StatusPictureItemWidth, height: StatusPictureItemWidth)
        let count = 3
        for i in 0..<count * count {
            let iv = UIImageView()
            // 设置 contentMode
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            // 行
            let row = CGFloat(i / count)
            // 列
            let col = CGFloat(i % count)
            // X 偏移量
            let xOffset = col * (StatusPictureItemWidth + StatusPictureViewInnerMargin)
            // Y 偏移量
            let yOffset = row * (StatusPictureItemWidth + StatusPictureViewInnerMargin)
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            addSubview(iv)
        }
    }
}
